package com.unismc.wixindemo.service.impl;

import com.unismc.wixindemo.entity.Data;
import com.unismc.wixindemo.service.ClientService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ClientServiceImpl implements ClientService {

	@Autowired
	private WxMpService wxMpService;
	
	private static final CloseableHttpClient httpclient = HttpClients.createDefault();



	@Override
	public void sendTemplate(Data data) {
			if(data.getKeyword3()==null) {
				if(data.getPerformance()==null) {
					WxMpTemplateMessage templateMessage = WxMpTemplateMessage
							.builder()
							.toUser("o_i5P1d5_wfN-bZRiTn88uuqnKy0")
							.templateId("pd_jDWhJP-1FT7dyxDFHuBMDnOQ7as4X7hsLMCk3NY0")
							.build();
					templateMessage.addData(new WxMpTemplateData("first",data.getFirst(),"#ffff"));
					templateMessage.addData(new WxMpTemplateData("keyword1",data.getKeyword1(),"#ffffff"));
					templateMessage.addData(new WxMpTemplateData("keyword2",data.getKeyword2(),"#ffffff"));
					templateMessage.addData(new WxMpTemplateData("remark",data.getRemark(),"#fffff"));
					try {
						wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
					} catch (WxErrorException e) {
						e.printStackTrace();
					}
				}
			}

	}

	@Override
	public String sendPost(String url, Map<String, String> map) {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpEntity entity1 = response.getEntity();
		String result = null;
		try {
			result = EntityUtils.toString(entity1);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}


}
